package com.losca.gulimall.auth.control;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.losca.common.utils.HttpUtils;
import com.losca.common.utils.R;
import com.losca.common.vo.MemberResponseVo;
import com.losca.gulimall.auth.feign.MemberFeignService;
import com.losca.gulimall.auth.vo.GiteeUser;
import com.losca.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static com.losca.common.constant.AuthServerConstant.LOGIN_USER;

@Controller
@Slf4j
public class OAuth2Controller {

    @Value("${oauth2.gitee.clientId}")
    private String clientId;
    @Value("${oauth2.gitee.clientSecret}")
    private String clientSecret;
    @Value("${oauth2.gitee.redirectUri}")
    private String redirectUri;

    @Resource
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam(value = "code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", clientId);
        map.put("client_secret", clientSecret);
        map.put("redirect_uri", redirectUri);
        map.put("code", code);
        map.put("grant_type", "authorization_code");
        // 根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
        // 处理
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到了access_token,转为通用社交登录对象
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            HashMap<String, String> map2 = new HashMap<>();
            map2.put("access_token", socialUser.getAccess_token());
            HttpResponse get = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map2);
            if (get.getStatusLine().getStatusCode() == 200) {
                String s = EntityUtils.toString(get.getEntity());
                GiteeUser giteeUser = JSON.parseObject(s, GiteeUser.class);
                socialUser.setUid(giteeUser.getId());
            }
            // 知道了哪个社交用户
            // 1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            // 登录或者注册这个社交用户
            // 调用远程服务
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if (oauthLogin.getCode() == 0) {
                MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功：用户信息：{}", data.toString());

                //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                //以后浏览器访问哪个网站就会带上这个网站的cookie
                //TODO 1、默认发的令牌。当前域（解决子域session共享问题）
                //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                session.setAttribute(LOGIN_USER, data);

                // 2、登录成功跳回首页
                return "redirect:http://mall.com";
            } else {
                return "redirect:http://auth.mall.com/login.html";
            }
        }else {
            return "redirect:http://auth.mall.com/login.html";
        }
    }

}
